import { UI } from '@/utils/UI';

export class Api {

    /**
     * 
     * @param response 
     * @param isPlan 返回的是否是 plain text
     * @param onError 错误回调
     */
    static processResponse<T>(response: Response, isPlan: boolean = false,
        onError: ((error: IApiException) => void) | undefined = undefined): Promise<T | null> {
        const status = response.status;
        let _headers: any = {};
        if (response.headers && response.headers.forEach) {
            response.headers.forEach((v: any, k: any) => _headers[k] = v);
        };
        if (status === 200) {
            return response.text().then((_responseText) => {
                return _responseText === "" ? null : (isPlan ? _responseText : JSON.parse(_responseText));
            });
        } else if (status !== 200 && status !== 204) {
            return response.text().then((_responseText) => {
                const ERROR_MESSAGE = "An unexpected server error occurred."
                if (typeof onError != "undefined") {
                    onError({
                        message: ERROR_MESSAGE,
                        status,
                        response: _responseText,
                        headers: _headers
                    })
                } else {
                    UI.errorNotification(`HTTP ${status}: ${response}`, ERROR_MESSAGE)
                }
                return null;
            });
        }
        return Promise.resolve<T>(<any>null);
    }

}

export interface IApiException {
    message: string
    status: number
    response: string
    headers: { [key: string]: any; }
}